package com.github.abdularis.sample;

import com.github.abdularis.buttonprogress.DownloadButtonProgress;
import ohos.eventhandler.EventHandler;

/**
 * Created by abdularis on 07/01/18.
 */
public class SampleTask implements Runnable {

    private int progress = 0;

    private final EventHandler handler;
    private final DownloadButtonProgress btnProgress;

    public SampleTask(EventHandler handler, DownloadButtonProgress btnProgress) {
        super();
        this.handler = handler;
        this.btnProgress = btnProgress;
    }

    @Override
    public void run() {
        try {
            setBtnIndeterminate();
            Thread.sleep(2000);
            setBtnDeterminate();
            while (progress <= 100) {
                Thread.sleep(30);
                progress++;
                setBtnProgress();
            }
            setBtnFinish();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void setBtnIndeterminate() {
        handler.postSyncTask(btnProgress::setIndeterminate);
    }

    private void setBtnDeterminate() {
        handler.postSyncTask(btnProgress::setDeterminate);
    }

    private void setBtnProgress() {
        handler.postSyncTask(() -> {
            btnProgress.setCurrentProgress(progress);
        });
    }

    private void setBtnFinish() {
        handler.postSyncTask(btnProgress::setFinish);
    }
}